﻿games.game2 = {
    played: new Array(),
    colors: "red,blue,green,yellow".split(","),
    clickIndex: 0,
    init: function () {
        var html = "<ul id='game2-pattern'>";
        for (var i = 0; i < this.colors.length; i++) {
            html += "<li><a href='#' class='" + this.colors[i] + "'>&nbsp;</li>";
        }
        html += "</ul>";
        $("#gamezone").html(html);
        games.game2.clickIndex = 0;
        this.played = new Array();
        setTimeout(function () {
            games.game2.playColours();
        }, 1000);
    },
    handlerUser: function () {
        games.game2.flashElement(0, $("#gamezone ul#game2-pattern li a." + $(this).attr("class")), false);
        if ($(this).attr("class") == games.game2.played[games.game2.clickIndex]) {
            games.game2.clickIndex++;
            if (games.game2.clickIndex == games.game2.played.length) {
                games.game2.clickIndex = 0;
                setTimeout(function () {
                    games.game2.playColours();
                }, 1000);
            }
        } else {
            alert("lost with a score of " + games.game2.played.length + ", resetting the game so you can try again. ");
            games.game2.init();
        }
    },
    playColours: function () {
        $("#gamezone ul#game2-pattern li a").unbind("click");
        this.played[this.played.length] = this.colors[games.helper.getRandomNumber(0, 4)];
        for (var i = 0; i < this.played.length; i++) {
            this.flashElement(i, $("#gamezone ul#game2-pattern li a." + this.played[i]), false);
        }
        this.flashElement(i + 1, $("<span>"), true);
    },
    flashElement: function (timeout, element, enableClick) {
        setTimeout(function () {
            element.addClass("play");
            setTimeout(function () {
                element.removeClass("play");
            }, 150);
            if (enableClick) {
                $("#gamezone ul#game2-pattern li a").click(games.game2.handlerUser);
            }
        }, 500 * timeout);
    }
};